<template>
  <div class="mobile-grid">
    <!-- 顶部工具栏 -->
    <div class="q-table__top row items-center justify-between q-px-md q-py-sm bg-white">
      <slot name="top-left">
        <div class="text-h6">{{ title }}</div>
      </slot>
      <slot name="top-right" />
    </div>

    <!-- 移动端数据展示 -->
    <div
      v-for="row in tableData"
      :key="row[rowKey]"
      class="mobile-card q-mb-md"
      :class="[rowClass ? rowClass(row) : '', { 'cursor-pointer': hasRowClick }]"
      @click="handleRowClick(row)"
    >
      <!-- 选择框和标题行 -->
      <div class="mobile-card-header row items-center q-px-sm q-py-md">
        <div v-if="selection" class="q-mr-md">
          <q-checkbox
            v-if="selection === 'multiple'"
            v-model="selectedRows"
            :val="row"
            @update:model-value="handleSelect(row)"
            @click.stop
          />
          <q-radio
            v-else-if="selection === 'single'"
            v-model="selectedRow"
            :val="row"
            @update:model-value="handleSelect(row)"
            @click.stop
          />
        </div>
        <!-- 显示第一列作为标题 -->
        <div class="text-weight-medium">
          {{ getColumnValue(row, columns[0]) }}
        </div>
      </div>

      <!-- 数据内容 -->
      <q-separator />
      <div class="mobile-card-body q-pa-md">
        <template v-for="col in displayColumns" :key="col.name">
          <div class="row q-mb-sm items-center">
            <div class="col-4 text-grey">{{ col.label }}:</div>
            <div class="col-8">
              <slot
                :name="`body-cell-${col.name}`"
                :row="row"
                :col="col"
                :value="getColumnValue(row, col)"
              >
                <template v-if="col.name === 'status'">
                  <q-chip
                    :color="getStatusColor(getColumnValue(row, col))"
                    text-color="white"
                    size="sm"
                  >
                    {{ getColumnValue(row, col) }}
                  </q-chip>
                </template>
                <template v-else>
                  {{ getColumnValue(row, col) }}
                </template>
              </slot>
            </div>
          </div>
        </template>
      </div>

      <!-- 操作按钮 - 修复后的版本 -->
      <template v-if="hasActionsColumn">
        <q-separator />
        <div class="mobile-card-actions q-pa-md">
          <div class="row justify-end q-gutter-sm">
            <!-- 默认操作按钮 -->
            <template v-if="defaultActions && defaultActions.length">
              <q-btn
                v-for="action in defaultActions"
                :key="action.label"
                :color="action.color || 'primary'"
                :icon="action.icon"
                :label="action.label"
                :disable="action.disable ? action.disable(row) : false"
                dense
                flat
                @click.stop="action.handler(row)"
              />
            </template>
          </div>
        </div>
      </template>
    </div>

    <!-- 分页器 - 完整版本 -->
    <div v-if="hasPagination" class="q-pa-md">
      <div class="row items-center justify-between q-col-gutter-md">
        <!-- 左侧信息 -->
        <div class="col-12 col-sm-auto text-grey text-center text-sm-left">
          显示第 {{ firstRowIndex }} - {{ lastRowIndex }} 条，共 {{ pagination.rowsNumber }} 条记录
        </div>

        <!-- 右侧分页控件 -->
        <div class="col-12 col-sm-auto row items-center justify-center justify-sm-end q-gutter-sm">
          <span class="text-grey-8">每页显示</span>
          <q-select
            v-model="rowsPerPage"
            :options="rowsPerPageOptions"
            dense
            options-dense
            borderless
            emit-value
            map-options
            style="min-width: 75px"
          />

          <q-pagination
            v-model="currentPage"
            :max="maxPage"
            :max-pages="5"
            :boundary-links="true"
            :direction-links="true"
            :boundary-numbers="false"
            dense
          >
            <template #first>
              <q-icon name="first_page" size="sm" />
            </template>
            <template #prev>
              <q-icon name="chevron_left" size="sm" />
            </template>
            <template #next>
              <q-icon name="chevron_right" size="sm" />
            </template>
            <template #last>
              <q-icon name="last_page" size="sm" />
            </template>
          </q-pagination>
        </div>
      </div>
    </div>

    <!-- 无数据时的提示 -->
    <template v-if="loading">
      <div class="full-width row flex-center q-pa-md text-grey">
        <q-spinner color="primary" size="2em" />
        <div class="q-ml-sm">加载中...</div>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, computed, watch, useSlots } from 'vue'

const slots = useSlots()

const props = defineProps({
  tableData: {
    type: Array,
    required: true,
  },
  columns: {
    type: Array,
    required: true,
  },
  title: {
    type: String,
    default: '',
  },
  rowKey: {
    type: String,
    default: 'id',
  },
  selection: {
    type: String,
    default: '',
  },
  selected: {
    type: [Array, Object],
    default: () => [],
  },
  loading: {
    type: Boolean,
    default: false,
  },
  pagination: {
    type: Object,
    default: () => ({
      sortBy: null,
      descending: false,
      page: 1,
      rowsPerPage: 10,
      rowsNumber: 0,
    }),
  },
  rowClass: {
    type: Function,
    default: null,
  },
  defaultActions: {
    type: Array,
    default: () => [],
    // 期望的格式:
    // [
    //   {
    //     label: '编辑',
    //     icon: 'edit',
    //     color: 'primary',
    //     handler: (row) => {},
    //     disable: (row) => boolean
    //   }
    // ]
  },
  rowsPerPageOptions: {
    type: Array,
    default: () => [5, 10, 15, 20, 30, 50, 100],
  },
})

const emit = defineEmits(['update:selected', 'selection', 'row-click', 'request'])

// 显示列（排除选择列和操作列）
const displayColumns = computed(() => {
  return props.columns.filter((col) => {
    // 处理 format 字段

    return col.name !== 'actions' && col.name !== 'selection' && col.name !== props.columns[0].name
  })
})

// 是否有操作列
const hasActionsColumn = computed(() => {
  return (
    props.columns.some((col) => col.name === 'actions') ||
    (props.defaultActions && props.defaultActions.length > 0)
  )
})

// 添加行点击检查
const hasRowClick = computed(() => {
  return !!slots['row-click']
})

// 选择相关
const selectedRows = ref([])
const selectedRow = ref(null)

// 分页相关计算属性
const hasPagination = computed(() => {
  return props.pagination && props.pagination.rowsNumber > 0
})

const maxPage = computed(() => {
  if (!props.pagination) return 1
  return Math.ceil(props.pagination.rowsNumber / props.pagination.rowsPerPage) || 1
})

const firstRowIndex = computed(() => {
  if (!props.pagination) return 0
  const { page, rowsPerPage } = props.pagination
  return (page - 1) * rowsPerPage + 1
})

const lastRowIndex = computed(() => {
  if (!props.pagination) return 0
  const { page, rowsPerPage, rowsNumber } = props.pagination
  return Math.min(page * rowsPerPage, rowsNumber)
})

// 分页相关响应式变量
const currentPage = ref(props.pagination?.page || 1)
const rowsPerPage = ref(props.pagination?.rowsPerPage || 10)

// 获取列值的方法
const getColumnValue = (row, col) => {
  const fieldValue = col.field || col.name
  const value = typeof fieldValue === 'function' ? fieldValue(row) : row[fieldValue]

  // 检查是否有 format 字段并应用格式化
  if (col.format) {
    return col.format(value) // 应用格式化函数
  }

  return value // 返回原始值
}

// 获取状态颜色
const getStatusColor = (status) => {
  const colors = {
    进行中: 'primary',
    已完成: 'positive',
    已逾期: 'negative',
    未开始: 'grey',
    在售: 'positive',
    缺货: 'negative',
  }
  return colors[status] || 'grey'
}

// 监听外部选中值变化
watch(
  () => props.selected,
  (newVal) => {
    if (props.selection === 'single') {
      selectedRow.value = newVal
    } else if (props.selection === 'multiple') {
      selectedRows.value = Array.isArray(newVal) ? [...newVal] : []
    }
  },
  { immediate: true, deep: true },
)

// 监听分页属性变化
watch(
  () => props.pagination,
  (newVal) => {
    if (newVal) {
      currentPage.value = newVal.page
      rowsPerPage.value = newVal.rowsPerPage
    }
  },
  { deep: true },
)

// 监听页码变化
watch(currentPage, (newVal) => {
  if (props.pagination && newVal !== props.pagination.page) {
    handlePageChange(newVal)
  }
})

// 监听每页条数变化
watch(rowsPerPage, (newVal) => {
  if (props.pagination && newVal !== props.pagination.rowsPerPage) {
    emit('request', {
      pagination: {
        ...props.pagination,
        page: 1,
        rowsPerPage: newVal,
      },
    })
  }
})

// 处理选择事件
const handleSelect = (row) => {
  if (props.selection === 'single') {
    selectedRow.value = row
    emit('update:selected', row)
    emit('selection', row)
  } else if (props.selection === 'multiple') {
    emit('update:selected', selectedRows.value)
    emit('selection', selectedRows.value)
  }
}

// 处理行点击
const handleRowClick = (row) => {
  emit('row-click', row)
}

// 处理分页变化
const handlePageChange = (page) => {
  if (props.pagination) {
    emit('request', {
      pagination: {
        ...props.pagination,
        page,
        rowsPerPage: rowsPerPage.value,
      },
    })
  }
}
</script>

<style lang="scss" scoped>
.mobile-grid {
  .mobile-card {
    background: white;
    border-radius: 8px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    overflow: hidden;

    &.cursor-pointer {
      cursor: pointer;
      transition: all 0.3s;
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
      }
    }

    &-header {
      background: rgba(0, 0, 0, 0.02);
    }

    &-body {
      .row {
        &:last-child {
          margin-bottom: 0;
        }
      }
    }

    &-actions {
      background: rgba(0, 0, 0, 0.02);

      .q-btn {
        min-width: 60px;

        &:not(:last-child) {
          margin-right: 8px;
        }
      }
    }
  }

  // 添加分页器样式
  :deep(.q-pagination) {
    .q-btn {
      padding: 4px 8px;
      min-height: 32px;
      min-width: 32px;
    }
  }

  :deep(.q-select) {
    .q-field__native {
      padding: 0;
    }

    .q-field__control {
      min-height: 32px;
    }
  }
}
</style>
